package com.shxc.smarttrade.account.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.base.BaseActivity;
import com.shxc.smarttrade.currency.model.CurrencyModel;
import com.shxc.smarttrade.dialog.WarningDialog;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.utils.AppUtils;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.ToastUtils;

import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 输入昵称
 */
@ContentView(R.layout.activity_account_name)
public class AccountNickActivity extends BaseActivity {

    @ViewInject(R.id.name_edittext)
    EditText name_edittext;
    @ViewInject(R.id.cancel_imageview)
    ImageView cancel_imageview;

    private InputMethodManager imm;

    private String nick;
    private WarningDialog warningDialog;

    @Event({R.id.cancel_textview, R.id.submit_textview,R.id.cancel_imageview})
    private void onClickk(View view) {

        switch (view.getId()) {
            case R.id.cancel_textview:
                //关闭
                finish();
                break;
            case R.id.submit_textview:
                //提交
                nick = name_edittext.getText().toString();
                if (AppUtils.isEmpty(nick)) {
                    warningDialog.showDialog("没有输入名字，请重新填写");
                    warningDialog.getCancel_textview().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            warningDialog.dismiss();
                        }
                    });
                }else{
                    editUserInfo();
                }
                break;
            case R.id.cancel_imageview:
                //清空
                name_edittext.setText("");
                cancel_imageview.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        cancel_imageview.setVisibility(View.GONE);
        name_edittext.setText(spImp.getNick());

        warningDialog = new WarningDialog(this, getResources().getIdentifier("MyDialog", "style", getPackageName()));

        name_edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    cancel_imageview.setVisibility(View.VISIBLE);
                    if (s.length() >= 10) {
                        s.delete(s.length() - 1, s.length());
                    }
                } else {
                    cancel_imageview.setVisibility(View.GONE);
                }
            }
        });
    }

    //用户信息修改(改)
    private void editUserInfo() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());
        map.put("nick", nick);
        map.put("sex", spImp.getSex());
        map.put("birthday",spImp.getBirthday());
        map.put("headUrl", spImp.getHeadUrl());
        map.put("introduction", spImp.getIntroduction());

        MyOkHttpUtils.getServiceDatas(map, Contents.ACCOUNT_EDITUSERINFO, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, CurrencyModel.class);
                    if (jam.isSuccess()) {
                        CurrencyModel model = (CurrencyModel) jam.getData();
                        if (model.getErr_code().equals("0")) {
                            spImp.setNick(nick);
                            ToastUtils.showToast("修改成功");
                            finish();
                        }else{
                            ToastUtils.showToast("网络错误，请重试");
                        }

                    } else {
                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    // 点击EditText以外的任何区域隐藏键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }
}
